#include "EchoServer.h"
#include <iostream>
#include <sstream>
#include <ctime>
#include <stdexcept>
#include <random>

using std::cout;
using std::endl;
using std::istringstream;
using std::ostringstream;
using std::to_string;
using std::exception;

EchoServer::EchoServer(const string &ip, unsigned short port, int subReactorNum, int threadNum, int queueSize)
: _threadPool(threadNum, queueSize)
, _server(ip, port, subReactorNum, &_threadPool)
, _taskManager(new TimerTask(this))
{

}

EchoServer::~EchoServer()
{

}

void EchoServer::start()
{
    //启动服务器之前：注册回调函数
    using namespace std::placeholders;
    _server.setAllCallback(std::bind(&EchoServer::onNewConnection,this,_1),
                           std::bind(&EchoServer::onMessage,this,_1),
                           std::bind(&EchoServer::onClose,this,_1));
    
    // 初始化定时任务
    initializeTasks();
    
    _server.start();
}

void EchoServer::stop()
{
    _server.stop();
}

void EchoServer::onNewConnection(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has connected." << endl;
    
    // 直接发送欢迎消息，避免跨线程定时器问题
    // cout << "[Connection] 立即发送欢迎消息" << endl;
    con->sendInLoop("=== Welcome to EchoServer！===\n");
    con->sendInLoop("支持的命令:\n");
    con->sendInLoop("  status - 查看服务器状态\n");
    con->sendInLoop("  time - 查看当前时间\n");
    con->sendInLoop("  delay <ms> <msg> - 延迟发送消息\n");
    // cout << "[Connection] 欢迎消息发送完成" << endl;
}



void EchoServer::onMessage(const TcpConnectionPtr &con)
{
    const string msg = con->receive();
    cout << ">>receive from client :" << msg << endl;

    // 处理特殊命令
    if (msg == "status\n")
    {
        con->sendInLoop("服务器状态: 运行正常\n当前时间: " + getCurrentTime() + "\n");
    }
    else if (msg == "time\n")
    {
        con->sendInLoop("当前时间: " + getCurrentTime() + "\n");
    }
    else if (msg.find("delay ") == 0)
    {
        handleDelayCommand(con, msg);
    }
    else if (msg == "dotask\n")
    {
        MyTask task(msg, con);
        _threadPool.addTask(std::bind(&MyTask::process, &task));
    }
    else
    {
        // 直接在当前线程中处理，或者通过TcpServer的ThreadPool处理
        con->sendInLoop("Echo: " + msg);
    }
}

void EchoServer::onClose(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has closed." << endl;
}

// 定时器接口实现
int64_t EchoServer::runAfter(std::chrono::milliseconds delay, TimerCallback &&callback)
{
    return _server.runAfter(delay, std::move(callback));
}

int64_t EchoServer::runEvery(std::chrono::milliseconds interval, TimerCallback &&callback)
{
    return _server.runEvery(interval, std::move(callback));
}

void EchoServer::cancelTimer(int64_t timerId)
{
    _server.cancelTimer(timerId);
}

void EchoServer::initializeTasks()
{
    cout << "=== 初始化定时任务 ===" << endl;

    // 注册各种定时任务
    _taskManager->registerHeartbeat();
    _taskManager->registerStatusReport();
    _taskManager->registerConnectionTimeout();
    _taskManager->registerWelcomeMessage();
    _taskManager->registerCleanupTask();

    // 示例：添加一个自定义的定时任务
    _taskManager->schedulePeriodicTask("连接统计", std::chrono::milliseconds(45000), []()
                                       {
                                           // cout << "[Statistics] 定期统计任务执行中..." << endl;
                                       });

    cout << "=== 定时任务初始化完成 ===" << endl;
}

string EchoServer::getCurrentTime()
{
    auto now = std::chrono::system_clock::now();
    auto time_t = std::chrono::system_clock::to_time_t(now);
    string timeStr = ctime(&time_t);
    // 移除换行符
    if (!timeStr.empty() && timeStr.back() == '\n')
    {
        timeStr.pop_back();
    }
    return timeStr;
}

void EchoServer::handleDelayCommand(const TcpConnectionPtr &con, const string &msg)
{
    // 解析命令格式: delay <milliseconds> <message>
    istringstream iss(msg);
    string cmd, delayStr, message;

    iss >> cmd >> delayStr;
    getline(iss, message);

    if (!message.empty() && message[0] == ' ')
    {
        message = message.substr(1); // 移除前导空格
    }

    try
    {
        int delay = stoi(delayStr);
        if (delay < 0 || delay > 300000)
        { // 最大5分钟
            con->sendInLoop("错误: 延迟时间必须在0-300000ms之间\n");
            return;
        }

        con->sendInLoop("已设置 " + to_string(delay) + "ms 延迟消息\n");

        // 设置延迟定时器
        runAfter(std::chrono::milliseconds(delay), [con, message, delay]()
                 {
            // cout << "[Timer] 定时器回调开始执行！delay=" << delay << "ms, message=" << message << endl;
            if (con->isClose()) {
                cout << "[Timer] 连接已关闭，取消发送延迟消息" << endl;
                return; // 连接已断开，直接返回
            }
            // cout << "[Timer] 连接正常，准备发送延迟消息" << endl;
            con->sendInLoop("[延迟 " + std::to_string(delay) + "ms] " + message + "\n");
            cout << "[Timer] 定时器任务完成: 延迟" << delay << "ms消息已发送" << endl; });
    }
    catch (const exception &e)
    {
        con->sendInLoop("错误: 无效的延迟时间格式\n");
    }
}

// 负载均衡接口实现
void EchoServer::setLoadBalanceStrategy(LoadBalanceStrategy strategy)
{
    _server.setLoadBalanceStrategy(strategy);
}

LoadBalanceStrategy EchoServer::getLoadBalanceStrategy() const
{
    return _server.getLoadBalanceStrategy();
}

std::pair<size_t, size_t> EchoServer::getConnectionRange()
{
    return _server.getConnectionRange();
}

// 连接数管理接口实现
void EchoServer::setMaxConnections(size_t maxConns)
{
    _server.setMaxConnections(maxConns);
}

size_t EchoServer::getMaxConnections() const
{
    return _server.getMaxConnections();
}
